package cc.rengu.redp.bizimpl.igas.service.impl;

import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.igas.domain.SDevBindInfo;
import cc.rengu.redp.bizimpl.igas.dao.SDevBindInfoMapper;
import cc.rengu.redp.bizimpl.igas.domain.SMchntBindInfo;
import cc.rengu.redp.bizimpl.igas.service.ISDevBindInfoService;
import cc.rengu.redp.bizimpl.igas.service.ISMchntBindInfoService;
import cc.rengu.redp.bizimpl.igas.vo.SDevBindInfoVO;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpBMchntBaseInfoService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpPrivilegeCheckService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysSeqService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.SortUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lizk
 */
@Service
@DS("igas")
public class SDevBindInfoServiceImpl extends ServiceImpl<SDevBindInfoMapper, SDevBindInfo> implements ISDevBindInfoService {


    @Autowired
    private ISMchntBindInfoService isMchntBindInfoService;
    @Autowired
    private IUpmpBMchntBaseInfoService iUpmpBMchntBaseInfoService;
    @Autowired
    private IUpmpSysSeqService sysSeqService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Value("${redp.max.batch.insert.num}")
    private int batchInsertMaxNum;
    @Autowired
    private IUpmpPrivilegeCheckService authPrivilegeCheckService;

    @Override
    public IPage<SDevBindInfo> findByPage(QueryRequest queryRequest, SDevBindInfo sDevBindInfo) {
        try {
            LambdaQueryWrapper<SDevBindInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(sDevBindInfo.getInstId())) {
                queryWrapper.eq(SDevBindInfo::getInstId, sDevBindInfo.getInstId());
            }
            if (!StringUtils.isEmpty(sDevBindInfo.getMsgPushKey())) {
                queryWrapper.like(SDevBindInfo::getMsgPushKey, sDevBindInfo.getMsgPushKey());
            }
            if (!StringUtils.isEmpty(sDevBindInfo.getBindDevType())) {
                queryWrapper.eq(SDevBindInfo::getBindDevType, sDevBindInfo.getBindDevType());
            }
            if (!StringUtils.isEmpty(sDevBindInfo.getBindStatus())) {
                queryWrapper.eq(SDevBindInfo::getBindStatus, sDevBindInfo.getBindStatus());
            }
            if (!StringUtils.isEmpty(sDevBindInfo.getBindMchntNo())) {
                queryWrapper.eq(SDevBindInfo::getBindMchntNo, sDevBindInfo.getBindMchntNo());
            }

            Page<SDevBindInfo> page = new Page<>();

            SortUtil.handlePageSort(queryRequest, page, true);

            //设置模型数量和商户名称
            Page<SDevBindInfo> infoPage = this.page(page, queryWrapper);
            for (SDevBindInfo bTermInfo : infoPage.getRecords()) {
                String bindMchntNo = bTermInfo.getBindMchntNo();
                String bindUserId = bTermInfo.getBindUserId();
                if (!StringUtils.isEmpty(bindMchntNo)) {
                    UpmpBMchntBaseInfo byMchntNo = iUpmpBMchntBaseInfoService.findByMchntNo(bindMchntNo);
                    if (Common.isNotBlank(byMchntNo)) {//修改时从数据库取realId
                        bTermInfo.setMchntName(byMchntNo.getMchntName());
                    }
                }

                if (StringUtils.isEmpty(bindMchntNo) || StringUtils.isEmpty(bindUserId)) {
                    bTermInfo.setBindNickName("");
                } else {
                    SMchntBindInfo sMchntBindInfo = isMchntBindInfoService.findBindNickName(bindMchntNo, bindUserId);

                    if (Common.isNotBlank(sMchntBindInfo)) {
                        bTermInfo.setBindNickName(sMchntBindInfo.getBindNickName());
                    } else {
                        bTermInfo.setBindNickName("");
                    }


                    //TODO 产品/品牌代码可能需要重新设值
                }
            }
            return infoPage;
        } catch (Exception e) {
            log.error("获取语音设备信息失败", e);
            return null;
        }
    }

    @Override
    public void createInfo(SDevBindInfo sDevBindInfo) throws RedpException {
        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:add");

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            String message = "不支持审核操作!";
            log.error(message);
            throw new RedpException(message);
        } else {
            String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            String time = DateUtils.formatDate(new Date(), "HHmmss");
            String date = DateUtils.formatDate(new Date(), "yyyyMMdd");
            //获取当前登录人信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            String NO = "MU" + String.format("%05d", Integer.parseInt(sysSeqService.updateParamValue(BusinessContainer.COMM_PARAM_CODE, BusinessContainer.DeviceNo_PREFIX, null)));
            sDevBindInfo.setBindDevId(NO);
            sDevBindInfo.setBindTime(time);
            sDevBindInfo.setBindDate(date);
            sDevBindInfo.setBindStatus("00");
            sDevBindInfo.setRecordStatus("Y");
            sDevBindInfo.setAuditStatus("02");
            sDevBindInfo.setBindDevType("02");//02-语音设备
            sDevBindInfo.setMsgPushFlag("N");
            sDevBindInfo.setOprId(user.getId());
            sDevBindInfo.setCreateTime(lastUpddt);
            this.save(sDevBindInfo);
        }
    }

    @Override
    public void updateInfo(SDevBindInfo sDevBindInfo) throws RedpException {

        //校验权限，是否需要审核
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:edit");

        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            String message = "不支持审核操作!";
            log.error(message);
            throw new RedpException(message);
        } else {
            String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            LambdaQueryWrapper<SDevBindInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SDevBindInfo::getInstId, sDevBindInfo.getInstId()).eq(SDevBindInfo::getBindDevType, sDevBindInfo.getBindDevType())
                    .eq(SDevBindInfo::getBindDevId, sDevBindInfo.getBindDevId());
            SDevBindInfo devBindInfo = this.getOne(wrapper);


            devBindInfo.setBindUserId(sDevBindInfo.getBindUserId());
            devBindInfo.setBindDevId(sDevBindInfo.getBindDevId());
            devBindInfo.setBindDevModel(sDevBindInfo.getBindDevModel());
            devBindInfo.setBindDevBrand(sDevBindInfo.getBindDevBrand());
            devBindInfo.setRemark5(sDevBindInfo.getRemark5());
            devBindInfo.setBindMchntNo(sDevBindInfo.getBindMchntNo());
            devBindInfo.setChainMchntNo(sDevBindInfo.getChainMchntNo());
            devBindInfo.setMsgPushFlag(sDevBindInfo.getMsgPushFlag());
            devBindInfo.setMsgPushKey(sDevBindInfo.getMsgPushKey());
            devBindInfo.setBindMchntType(sDevBindInfo.getBindMchntType());
            devBindInfo.setRecordStatus("Y");
            devBindInfo.setAuditStatus("42");
            //获取当前登录人信息
            UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
            devBindInfo.setLastAuditId(user.getId());
            devBindInfo.setLastUpdateTime(lastUpddt);

            LambdaUpdateWrapper<SDevBindInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(SDevBindInfo::getInstId, devBindInfo.getInstId()).eq(SDevBindInfo::getBindDevType, devBindInfo.getBindDevType())
                    .eq(SDevBindInfo::getBindDevId, devBindInfo.getBindDevId());

            this.update(devBindInfo, updateWrapper);

        }


    }


    @Override
    public void updateDevBindInfoStatus(SDevBindInfo sDevBindInfo) throws RedpException {

        String flag = sDevBindInfo.getStatusChangeFlag();
        //获取当前登录人信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        //22-停用审核通过
        String auditStatus = "";
        String recordStatus = "";
        UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();

        LambdaQueryWrapper<SDevBindInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SDevBindInfo::getInstId, sDevBindInfo.getInstId()).eq(SDevBindInfo::getBindDevType, sDevBindInfo.getBindDevType())
                .eq(SDevBindInfo::getBindDevId, sDevBindInfo.getBindDevId());
        SDevBindInfo devBindInfo = this.getOne(wrapper);

        if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag) || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag) || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(flag)) {
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    String message = "不支持审核操作!";
                    log.error(message);
                    throw new RedpException(message);
                } else {
                    auditStatus = "22";
                    recordStatus = "N";
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(flag)) {
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    String message = "不支持审核操作!";
                    log.error(message);
                    throw new RedpException(message);
                } else {
                    auditStatus = "32";
                    recordStatus = "Y";
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(flag)) {
                privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    String message = "不支持审核操作!";
                    log.error(message);
                    throw new RedpException(message);
                } else {
                    auditStatus = "12";
                    recordStatus = "N";
                }
            }
            devBindInfo.setAuditStatus(auditStatus);
            devBindInfo.setRecordStatus(recordStatus);

        } else if ("bind".equals(flag)) {
            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:bind");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                String message = "不支持审核操作!";
                log.error(message);
                throw new RedpException(message);
            } else {
                devBindInfo.setBindUserId(sDevBindInfo.getBindUserId());
                devBindInfo.setBindDevId(sDevBindInfo.getBindDevId());
                devBindInfo.setBindDevModel(sDevBindInfo.getBindDevModel());
                devBindInfo.setRemark5(sDevBindInfo.getRemark5());
                devBindInfo.setBindMchntNo(sDevBindInfo.getBindMchntNo());
                devBindInfo.setChainMchntNo(sDevBindInfo.getChainMchntNo());
                devBindInfo.setBindMchntType(sDevBindInfo.getBindMchntType());
                devBindInfo.setRecordStatus("Y");
                devBindInfo.setAuditStatus("42");
                devBindInfo.setBindStatus("00");

                devBindInfo.setLastAuditId(user.getId());
                devBindInfo.setLastUpdateTime(lastUpddt);
            }
        } else if ("unbind".equals(flag)) {
            privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(sDevBindInfo.getInstId(), "devBindInfo:cancel");
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                String message = "不支持审核操作!";
                log.error(message);
                throw new RedpException(message);
            } else {
                devBindInfo.setAuditStatus("42");
                devBindInfo.setBindStatus("01");
                devBindInfo.setLastAuditId(user.getId());
                devBindInfo.setLastUpdateTime(lastUpddt);
            }
        }

        LambdaUpdateWrapper<SDevBindInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SDevBindInfo::getInstId, devBindInfo.getInstId()).eq(SDevBindInfo::getBindDevType, devBindInfo.getBindDevType())
                .eq(SDevBindInfo::getBindDevId, devBindInfo.getBindDevId());

        this.update(devBindInfo, updateWrapper);

    }

    @Override
    public boolean isExit(String bindDevId) {
        LambdaQueryWrapper<SDevBindInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SDevBindInfo::getBindDevId, bindDevId);
        SDevBindInfo devBindInfo = this.getOne(wrapper);
        if (ObjectUtils.isEmpty(devBindInfo)) {
            return true;
        }
        return false;
    }

    @Override
    public void batchInsert(List<SDevBindInfoVO> data) throws RedpException {
        //TODO 没有限制导入的条数
        UpmpPrivilegeCheck privilegeCheck = authPrivilegeCheckService.getPrivilegeCheckByPrivilegeCode(data.get(0).getInstId(), "devBindInfo:add");
        if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
            String message = "不支持审核操作!";
            log.error(message);
            throw new RedpException(message);
        } else {
            String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
            String time = DateUtils.formatDate(new Date(), "HHmmss");
            String date = DateUtils.formatDate(new Date(), "yyyyMMdd");
            List<SDevBindInfo> insertList = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                SDevBindInfo devbindinfo = new SDevBindInfo();

                BeanUtils.copyProperties(data.get(i), devbindinfo);
                //获取当前登录人信息
                UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
                devbindinfo.setCreateTime(lastUpddt);
                devbindinfo.setBindTime(time);
                devbindinfo.setBindDate(date);
                devbindinfo.setBindStatus("01");
                devbindinfo.setBindDevType("02");//02-语音设备
                devbindinfo.setMsgPushFlag("Y");
                devbindinfo.setMsgPushKey(data.get(i).getMsgPushKey());
                devbindinfo.setRecordStatus("Y");
                devbindinfo.setAuditStatus("02");//新增审批通过
                devbindinfo.setOprId(user.getId());
                devbindinfo.setLastAuditId(user.getId());
                devbindinfo.setLastAuditTime(lastUpddt);

                insertList.add(devbindinfo);
            }
            this.saveBatch(insertList, batchInsertMaxNum);

        }
    }

    @Override
    public List<SMchntBindInfo> findBindUserId(String bindMchntNo) {
        return isMchntBindInfoService.findBindUserId(bindMchntNo);
    }
}
